package com.example.hanchen.yongkanggy.http;

import android.text.TextUtils;
import android.util.Log;


import com.example.hanchen.yongkanggy.entity.StatusCode;
import com.example.hanchen.yongkanggy.utils.BasicInformationUtils;
import com.example.hanchen.yongkanggy.utils.Md5Utils;
import com.example.hanchen.yongkanggy.utils.PreferencesUtil;
import com.example.hanchen.yongkanggy.utils.QueryStringSorter;
import com.example.hanchen.yongkanggy.utils.SharePreferencesConsts;
import com.example.hanchen.yongkanggy.utils.String16BitUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/*请求头封装*/
public class HeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        StatusCode statusCode = PreferencesUtil.getObject(SharePreferencesConsts.LOGINSMS, StatusCode.class);

        /*API接口签名*/
        long timestamps = System.currentTimeMillis();/*时间戳*/
        String verificationStr = String16BitUtils.generateRandomNumberAndLetters(16);/*16位的随机数*/
        String apiSign = Md5Utils.getMD5String(verificationStr + ConstantData.APISECRETKEY + String.valueOf(timestamps));
        Request original = chain.request();

        String parameterSign = null;
        String s1 = null;
        if (original.body() != null) {
            // 读取请求体并打印（注意：某些类型的请求体只能读取一次）
            String bodyContent = printRequestBody(original.body());
            s1 = QueryStringSorter.cleanEmptyParams(decodeUtf8Escapes(bodyContent));

            if (!TextUtils.isEmpty(s1)) {
                parameterSign = Md5Utils.getMD5String(s1 + "&" + ConstantData.BUSINESSSECRETKEY);
            } else {
                parameterSign = Md5Utils.getMD5String(ConstantData.BUSINESSSECRETKEY);
            }
        }
        /*请求头*/
        Request.Builder requestBuilder = original.newBuilder()
                .addHeader("Connection", "close")
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("timestamp", String.valueOf(timestamps))
                .addHeader("verificationStr", verificationStr)
                .addHeader("apiSign", apiSign)
                .addHeader("parameterSign", parameterSign)
                .addHeader("channel", "2")/*1 小程序  2  安卓 3 ios*/
                .addHeader("model", android.os.Build.MODEL)
                .addHeader("api_token", statusCode != null ? statusCode.getData().getTokenValue() : "")
                .addHeader("version", BasicInformationUtils.getVersionName());

        Request request = requestBuilder.build();
        long endTime = System.currentTimeMillis();
        long duration = endTime - timestamps;
        Log.i("TAG", "----------Request Start----------------");
        Log.i("TAG", "| " + request.toString() + "===========" + request.headers().toString());
        Log.i("TAG", "=====请求地址======" + request.url() + "  =====请求参数======  " + s1 + "    ");// + "    " + + response.body().string()

        Response response = chain.proceed(request);
        String responseBodyString = response.body().string();
        Log.i("TAG", "----------Request End:" + duration + "   " + request.url() + "回调参数");
        Log.i("TAG", "----------Request End:" + duration + "   " + request.url() + "回调参数" + responseBodyString);
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), responseBodyString))
                .build();
    }


    /*包含UTF-8的数据转成中文*/
    public static String decodeUtf8Escapes(String input) {
        if (input == null) {
            return null;
        }
        try {
            // 尝试解码整个字符串，这里使用UTF-8编码
            return URLDecoder.decode(input, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // UTF-8是Java标准支持的，所以这里基本上不会抛出异常
            e.printStackTrace();
            return input; // 或者你可以选择返回一个错误消息或null
        }
    }


    public static String printRequestBody(RequestBody requestBody) throws IOException {
        // 创建一个新的缓冲区
        Buffer buffer = new Buffer();
        if (requestBody != null) {
            // 将请求体写入缓冲区
            requestBody.writeTo(buffer);
            // 返回缓冲区内容的字符串表示形式
            return buffer.readUtf8();
        }
        return null;
    }
}
